<template>
  
</template>

<script lang="ts" setup>
import { inject, onMounted, ref, watch, computed, onUnmounted, onBeforeUnmount } from 'vue';
import { useEmitt } from '@sutpc/vue3-hooks';
import config from '@/global/config'
import { useUserStore } from '@/store/user';
import { getStaticFile } from '@sutpc/axios';
import { getCloudFileHref, getFileByStatic } from '@/utils/index'
import { getTiannetApi, searchRoadApi } from '@/utils/api';
import { formItemValidateStates } from 'element-plus';


defineOptions({
  name: 'RoadLayer'
})

const { emitter } = useEmitt();
const main = inject<any>('main');
const { mapInstance, components, AC_NAME }: any = main;
const userStore = useUserStore()

// 初始化路口态势
const initRoadLayer = async () => {
  await mapInstance.value.acApi.camera.set(536491.8625, 2510202.08, 1000, -83.974602, -114.262474)
  searchRoadApi('').then(res => {
    console.log(res)
    userStore.setSearchValueId(res[0].code)
    // console.log(res)
    // if (res.length === 1){
    //   // console.log(Number(res[0].lng), Number(res[0].lat))
    //   // console.log(Number(res[0].lat));
    //   mapInstance.value.acApi.coord.gcs2pcs([Number(res[0].lng), Number(res[0].lat)], 1, (e) => {
    //     // console.log(e)
    //     mapInstance.value.acApi.camera.set(e.coordinates[0][0], e.coordinates[0][1], 174.407129, -83.974602, -114.262474, () => {
    //       // userStore.isShowMenu(true)
    //       // clearPerception()
    //       // roadDelPolyline()
    //       // userStore.setShowVideo(false)
    //       // equAdd(res[0].id)
    //       topicVehicle()
    //     })
    //   })
    // }
  })
}

// 计算车辆数据
const vehicleData = computed(() => {
  return userStore.vehicleData
})
// 声明删除
let delArr = []
// // 声明所有创建的车辆
const allVehicle = ref([])
// // 监听车辆数据变化，如果没有创建新车辆，如果有了更新车辆数据 testData vehicleData
watch(vehicleData, async (newVal) => {
  // console.log(newVal)
  if (newVal) {
    // 如果有新增车辆
    if (newVal.add.length !== 0) {
      await mapInstance.value.acApi.vehicle.add(newVal.add, (e) => {
        // 创建车辆成功后，如果allVehicle里没有创建的车辆，就把创建的车辆保存到allVehicle里
        newVal.add.forEach(item => {
          if (!allVehicle.value.includes(item.id)) {
            allVehicle.value.push(item.id)
          }
        })
      })
    }
    // 如果传入车辆移动点位
    if (newVal.moveTo.length !== 0) {
      await mapInstance.value.acApi.vehicle.moveTo(newVal.moveTo)
      // console.log('车辆正在移动')

        let moveToIds = newVal.moveTo.map(item => item.id)
        for (let i = allVehicle.value.length - 1; i >= 0; i--) {
          if (!moveToIds.includes(allVehicle.value[i])) { 
            delArr.push(allVehicle.value[i])
            allVehicle.value.splice(i, 1)
          }
        }
        if(delArr.length){
          await mapInstance.value.acApi.vehicle.delete(delArr)
          delArr = []
        }
    }
  }
})
// 清空场景中所有Vehicle对象
const clearVehicle = async () => {
//  console.log('点击清空车辆')
 const res = await mapInstance.value.acApi.vehicle.clear()
//  console.log(res)
}

// 调用基座库 mapInstance.value.mapClass.EventClass中的方法:
// addEventByKey: (key: string, eventHandler: any) => void
// removeEventByKey : (key:string) => void

// 用法：
const EVENT_HANDLER  = 'TIAN-POLYGON-PICK'

// // 初始化时注册
if (mapInstance.value){
  mapInstance.value.mapClass.EventClass.addEventByKey(EVENT_HANDLER  , async (e) => {
    // console.log('天安' , e)
    if (e.Type === 'CustomObj') {
      // createVehicleWindow()
      mapInstance.value.acApi.marker.setAttachCustomObject({
        markerId: 'vehicleWindow',
        objectId: 'o1'
      }, (e) => {
        // console.log(e)
      })
    }
    if (e.UserData) {
      const userData = JSON.parse(e.UserData)
      // 点击雷达图标获取雷达感知
      if (userData.typeId === 103) {
        // 地理坐标转投影坐标
        mapInstance.value.acApi.coord.gcs2pcs([userData.lat, userData.lon], 1, (p) => {
          // console.log(p.coordinates[0][0], p.coordinates[0][1])
          mapInstance.value.acApi.radiationPoint.add({
            id: e.Id,
            groupId: e.GroupID,
            coordinate: [p.coordinates[0][0], p.coordinates[0][1]],
            radius: 10,
            rippleNumber: 2,
            color: '#FFFEEE',
            intensity: 0.5,
            autoHeight: false
          })
        })
      }
      if (userData.typeId === 102) {
        drawCameraRadius()
      }
      // 获取通行方向车道
      if (userData.typeId === 101) {
        roadPolyline()
      }
    }
  })
}
// 点聚合实现
const createCustomClusterMarker = () => {
  console.log('创建点聚合')
}

// 绘制摄像机照射范围
const drawCameraRadius = async () => {
  await mapInstance.value.acApi.polygon.add({
    id: 'cameraRadius',
    groupId: 'cameraRadius',
    userData: '',
    depthTest: false,
    color: '#13C6E6',
    coordinates:  [[114.361553, 22.680208], [114.361579, 22.680097],[114.362771, 22.680349], [114.362756, 22.68045], [114.362222, 22.680331], [114.361892, 22.680284]],
    coordinateType: 1,
    style: 6
  })
}

// 删除摄像机照射范围
const clearCamerRaidus = async () => {
  await mapInstance.value.acApi.polygon.clear()
}

// 创建道路通向Polyline
const roadPolyline = () => {
  getStaticFile('[publicPath]static/jsons/eqq.json').then((jsonData) => {
    mapInstance.value.acApi.polyline.add({
      id: 'roadPolyline',
      groupId: 'groupRoadPolyline',
      coordinates: [[114.362415, 22.680026], [114.362356, 22.680114], [114.362341, 22.680163], [114.362346, 22.680204], [114.362377, 22.680263], [114.362421, 22.680287], [114.362462, 22.680299], [114.362578, 22.680327]],
      coordinateType: 1,
      range: [1, 100000], //可视范围：[近裁距离, 远裁距离]，取值范围: [任意负值, 任意正值]
      color: [0.13, 0.65, 0.73, 0.8], //多边形的填充颜色
      frameColor: '#ffffff', //边框颜色
      frameThickness: 50, //边框厚度
      intensity: 10, //亮度
      style: 1, //单色 请参照API开发文档选取枚举
      depthTest: false //是否做深度检测 开启后会被地形高度遮挡
    }, () => {
      // console.log('创建roadPolygon')
    })
  })
}
// 删除道路通向Polyline
const roadDelPolyline = () => {
  mapInstance.value.acApi.polyline.delete('roadPolyline')
}

// 创建设备图标
const equAdd = (junctionId) => {
  // 调用路口路测设备接口
  getTiannetApi(junctionId).then((jsonData) => {
    // console.log(jsonData.detailInfo)
    mapInstance.value.acApi.marker.clear()
    userStore.setEquList(jsonData.detailInfo)
    userStore.setEquId(jsonData.detailInfo[0].typeId)
    mapInstance.value.acApi.marker.add(createMarkerData(userStore.equList[0].childs), () => {
      // console.log('创建路口设备')
    })
  })
}

// 清除雷达感知
const clearPerception = async () => {
  await mapInstance.value.acApi.radiationPoint.clear(() => {
    // console.log('清除雷达感知')
  })
}

// 删除设备点位
const equDelete = async () => {
  await mapInstance.value.acApi.marker.clear()
}
// const staticIP = 'http://10.9.100.82:10001'
// 根据设备id定义创建marker时的数据
const createMarkerData = (data) => {
  const arr = []
  // console.log(getCloudFileHref())
  data.map((item) => {
    let obj = {
      id: item.id,
      groupId: `${item.id}`,
      userData: JSON.stringify(item),
      coordinateType: 1,
      coordinate: [item.lat, item.lon],
      useTextAnimation: false,
      textRange: [1, 1000],//文本可视范围[近裁距离, 远裁距离]
      textOffset: [0, 0],// 文本偏移
      textBackgroundColor: Color.SpringGreen,//文本背景颜色
      anchors: [15, 55],
      imageSize: [30, 55],
      fixedSize: false,
      imagePath: '',
      displayMode: 2
    }
    // console.log(staticIP + '[publicPath]static/images/icon_xinhaodeng.png')
    if (item.typeId === '009') {
      obj.imagePath = getCloudFileHref('images/icon_xinhaodeng.png')
      // obj.imagePath = staticIP + '[publicPath]static/images/icon_xinhaodeng.png'
      // console.log(getFileByStatic('images/icon_xinhaodeng.png'))
      // obj.imagePath = getFileByStatic('images/icon_xinhaodeng.png')
      console.log(obj.imagePath)
    }
    if (item.typeId === '003') {
      obj.imagePath = getCloudFileHref('images/icon_shexiangji.png')
      // obj.imagePath = staticIP + '[publicPath]static/images/icon_shexiangji.png'
      // obj.imagePath = getFileByStatic('images/icon_shexiangji.png')
      console.log(obj.imagePath)
    }
    if (item.typeId === '004') {
      obj.imagePath = getCloudFileHref('images/icon_leida.png')
      // obj.imagePath = staticIP + '[publicPath]static/images/icon_leida.png'
      // obj.imagePath = getFileByStatic('images/icon_leida.png')
      console.log(obj.imagePath)
    }
    if (item.typeId === '001') {
      obj.imagePath = getCloudFileHref('images/icon_rsu.png')
      // obj.imagePath = staticIP + '[publicPath]static/images/icon_rsu.png'
      // obj.imagePath = getFileByStatic('images/icon_rsu.png')
      console.log(obj.imagePath)
    }
    if (item.typeId === '002') {
      obj.imagePath = getCloudFileHref('images/icon_mec.png')
      // obj.imagePath = staticIP + '[publicPath]static/images/icon_mec.png'
      // obj.imagePath = getFileByStatic('images/icon_mec.png')
      console.log(obj.imagePath)
    }
    // console.log(obj)
    arr.push(obj)
  })
  // console.log(arr)
  return arr
}

// 更新设备点位 用于切换对应设备点位位置、icon、数据
const equUpdate = (data) => {
  // console.log(data.childs)
  mapInstance.value.acApi.marker.clear()
  mapInstance.value.acApi.marker.add(createMarkerData(data.childs), () => {
    // console.log('成功添加设备点位')
  })
}

// 订阅路口车流数据
const topicVehicle = () => {
  userStore.initMqttVehicle(`ROAD-${config.CLIENT_ID}`)
}
// 使用emit，点击index交互，传值给layer页面
// 路口设备菜单
const equList = computed(() => {
  return userStore.getEquList
})
// 获取设备id，用来做点击切换设备，获取对应设备下数据
const equId = computed(() => {
  return userStore.getEquId
})
const changeEquType = (params) => {
  // console.log(params)
  userStore.setEquId(params.typeId)
  clearPerception()
  clearCamerRaidus()
  roadDelPolyline()
  // // 判断摄像机显示视频
  if (userStore.equId === 102) {
    userStore.setShowVideo(true)
  } else {
    userStore.setShowVideo(false)
  }
  let imgUrl = params.url
  let selUrl = imgUrl.replace('_nor', '_sel')
  for (let i = 0; i < equList.value.length; i++) {
    if (equList.value[i].typeId === equId.value) {
      equList.value[i].imageUrl = selUrl
      equUpdate(equList.value[i])
    }
    if (equList.value[i].typeId !== equId.value) {
      let norUrl =  equList.value[i].imageUrl.replace('_sel', '_nor')
      equList.value[i].imageUrl = norUrl
    }
  }
}
// 交互事件常量
const EVENT_EQU_TYPE = 'CHANGE_EQU'
const EVENT_BACK_HOME = 'BACK_TIANPINGSHAN_HOME'
const EVENT_SEARCH_ROAD = 'SEARCH_ROAD'
emitter.on(EVENT_EQU_TYPE, changeEquType)

// 返回坪山全景
const backpingshanhome = () => {
  userStore.setSearchValue('')
  userStore.setShowSearchRoadValue(false)
  equDelete()
  userStore.closeMqttClient()
  clearPerception()
  clearVehicle()
  // getPingshan()
  roadDelPolyline()
  userStore.setEquId(0)
  userStore.setShowVideo(false)
  userStore.setSowLevel3(false)
}

// 搜索路口
const searchRoad = (params) => {
  searchRoadApi('坪山大道-横岭路').then(res => {
    // console.log(res)
    if (res.length === 1){
      // console.log(Number(res[0].lng), Number(res[0].lat))
      // console.log(Number(res[0].lat));
      mapInstance.value.acApi.coord.gcs2pcs([Number(res[0].lng), Number(res[0].lat)], 1, (e) => {
        // console.log(e)
        mapInstance.value.acApi.camera.set(e.coordinates[0][0], e.coordinates[0][1], 174.407129, -83.974602, -114.262474, () => {
          // userStore.isShowMenu(true)
          // clearPerception()
          // roadDelPolyline()
          // userStore.setShowVideo(false)
          // equAdd(res[0].id)
          topicVehicle()
        })
      })
    }
  })
}
emitter.on(EVENT_SEARCH_ROAD, searchRoad)

onMounted(() => {
  initRoadLayer()
})
// 组件卸载时移除
onUnmounted(() => {
  emitter.off(EVENT_EQU_TYPE, changeEquType )
  emitter.off(EVENT_BACK_HOME, backpingshanhome )
  emitter.off(EVENT_SEARCH_ROAD, searchRoad )
  // if(mapInstance.value) {
  //   mapInstance.value.mapClass.EventClass.removeEventByKey(EVENT_HANDLER);
  // }
})

</script>

<style>

</style>